<template>
  <div :style="{ paddingBottom: accountInfoBoxBottom }" class="account-info-container">
    <div class="title-row">
      <SectionTitle title="账号信息"/>
      <div v-if="!isModify" class="flex">
        <PlainCreateBtn class="create-btn" @click="addAccount">关联账号</PlainCreateBtn>
        <PlainCreateBtn v-if="!showMobilePage" class="create-btn" size="small" @click="toCreate">新建账号</PlainCreateBtn>
        <el-button size="small" plain style="width: 80px;display: flex;justify-content: center;" @click="handleBatchDelete">取消关联</el-button>
        <el-button v-if="showMobilePage" size="small" type="text" @click="toCreate">新建账号</el-button>
      </div>
    </div>
    <el-table
      ref="accountTableRef"
      :data="listData"
      class="fb-table"
      header-cell-class-name="order-data-header-cell"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      fit
      select-callback
      hightlight-current-rowref="tableRef"
      @select="selectTable"
      @select-all="selectTable">
      <emptyPlaceholder slot="empty" />
      <el-table-column
        fixed="left"
        align="center"
        type="selection"
        width="50"
      />
      <el-table-column align="left" label="账号" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.baseInfo.accountName" is-can-click @handelClick="toAccountDetail(scope.row.id)" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="平台" min-width="120">
        <template slot-scope="scope">
          <div class="flex">
            <platformIcon :data="scope.row.platformTypeName" />
            <ToolTip :content="scope.row.platformTypeName"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="账号ID" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.baseInfo.accountId"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="链接" min-width="150">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.resourceLink" :is-can-click="!!scope.row.resourceLink" @handelClick="openLink(scope.row.resourceLink)"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="运营模式" min-width="150">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.operateModeName"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="是否挂靠" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.microTask ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" label="签约状态" min-width="190">
        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.signDetailStatus || scope.row.signDetailStatus === 0" :open-delay="800" class="sign-status-tooltip" placement="top">
            <div slot="content" class="tooltip-content">
              <div class="account-item-tip"> {{ scope.row.signDetailStatus | signStatusFilter }} <br></div>
            </div>
            <div>
              <StatusText
                :color="getColor(scope.row.signDetailStatus)"
                :text="scope.row.signDetailStatus | signStatusFilter"
              />
            </div>
          </el-tooltip>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="签单签约经纪" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.additionalKey.contractBroker"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="签约有效期" min-width="200">
        <template slot-scope="scope">
          <ToolTip :content="`${format(scope.row.signStartDate, 'YYYY/MM/DD')}-${format(scope.row.signEndDate, 'YYYY/MM/DD')}`"/>
        </template>
      </el-table-column>
      <el-table-column align="left" label="关联合同" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.legalCode ? scope.row.legalCode.contractCode : ''" :is-can-click="!!scope.row.legalCode" @handelClick="toContractDetail(scope.row.legalCode)" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="合作方式" min-width="120">
        <template slot-scope="scope">
          <ToolTip :content="scope.row.additionalKey.cooperationOption | cooperationStatusFilter"/>
        </template>
      </el-table-column>
      <el-table-column v-if="!isModify" align="left" label="操作" width="80" fixed="right">
        <template slot-scope="scope">
          <div class="operate-delete" @click="handleDelete(scope.row.mediumId)">取消关联</div>
        </template>
      </el-table-column>
    </el-table>
    <template v-if="list.total > 10">
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page="page"
          :page-size="perPage"
          :total="list.total"
          :page-sizes="[10, 20, 50, 100]"
          :layout="pageLayout"
          :small="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
      <div v-if="!showMobilePage" class="select-row">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page="page"
          :page-size="perPage"
          :total="list.total"
          :page-sizes="[10, 20, 50, 100]"
          :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </template>
    <AccountSelection
      ref="accountSelection"
      :visible.sync="showAccountSelection"
      @submit="selectAccount"
    />
  </div>
</template>

<script>
import ListTab from '@/components/ListTab';
import SectionTitle from '@/components/Title';
import FileShowList from '@/components/CreateOrder/fileShowList';
import PlatformIcon from '@/components/Common/platformIcon';
import linkImg from '@/assets/medium/link.png';
import { SUPPLIER_DETAIL_TYPE } from '@/utils/const/supplier';
import { encryption } from '@/utils';
import { format } from '@/filters/date';
import { delResource } from '@/api/supplier';
import { hasRouteAuth } from '@/utils/permission';
import emptyIcon from '@/assets/home/emptyIcon.png';
import { formatValue } from '../filters/index';
import { signStatusFilter, getSignUpColor } from '@/filters/status';
import sensitiveInfo from '@/components/SupplierComponent/sensitiveInfo';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import AccountSelection from '@/components/resource/AccountSelection';
import tableSelections from '@/mixins/tableSelections';
import emptyPlaceholder from '@/components/Common/emptyPlaceholder';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import mobileTable from '@/mixins/mobileTable';
import { cooperationStatusFilter } from '@/utils/accountCommonData';
import { resourceAssociation } from '@/api/supplier';
export default {
  name: 'SupplierAccountInfo',
  components: {
    ListTab,
    PlatformIcon,
    FileShowList,
    sensitiveInfo,
    DetailTabs,
    SectionTitle,
    AccountSelection,
    EmptyPlaceholder,
    emptyPlaceholder
  },
  filters: { formatValue, signStatusFilter, format, cooperationStatusFilter },
  mixins: [tableSelections, mobileTable],
  props: {
    accountsInfoList: {
      type: Array,
      default: () => []
    },
    supplierDetailInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    detailType: {
      type: Number,
      default: SUPPLIER_DETAIL_TYPE.SUPPLIER
    },
    contractCodeViewStatus: {
      type: Boolean,
      default: false
    },
    supplierId: {
      type: Number,
      default: null
    },
    isShowSignUp: {
      type: Boolean,
      default: false
    },
    parentSupplierId: {
      type: Number,
      default: null
    },
    inSubTab: {
      type: Boolean,
      default: false
    },
    isModify: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      linkImg,
      emptyIcon,
      accountIndex: 0,
      accountList: [],
      formData: [],
      showAccountSelection: false,
      tableRefName: 'accountTableRef',
      isUmyTable: false,
      idKey: 'mediumId',
      page: 1,
      perPage: 10,
      list: {
        items: [],
        total: 0
      }
    };
  },
  computed: {
    labelWidth() {
      return this.detailType === SUPPLIER_DETAIL_TYPE.SUPPLIER ? '6em' : '8em';
    },
    accountInfoBoxBottom() {
      return this.detailType === SUPPLIER_DETAIL_TYPE.SUPPLIER ? '10px' : '60px';
    },
    paramsObj() {
      const { type } = this.$route.query;
      return {
        type: 0,
        fieldType: 0,
        channelId: type ? this.parentSupplierId : this.supplierId
      };
    },
    listData() {
      return this.list.items.slice((this.page - 1) * this.perPage, this.page * this.perPage);
    }
  },
  watch: {
    listData: {
      handler(val) {
        if (!val.length && this.page !== 1) {
          this.page--;
        }
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val);
        });
      },
      deep: true
    },
    accountsInfoList: {
      handler(val) {
        if (!val.length) {
          this.list.items = [];
          this.list.total = 0;
          return;
        }
        this.list.items = val.map(it => {
          return {
            ...it.accountsInfo,
            ...it.contractInfo,
            baseInfo: {
              accountName: it.accountsInfo.accountName,
              accountId: it.accountsInfo.accountCode
            },
            additionalKey: {
              contractBroker: it.contractInfo.agentName,
              cooperationOption: it.accountsInfo.cooperationOption
            },
            platformTypeName: it.accountsInfo.plateformName,
            mediumId: it.accountsInfo.id,
            accountId: it.accountsInfo.accountCode,
            operateModeName: it.accountsInfo.operatingModelName,
            resourceLink: it.accountsInfo.link
          };
        });
        this.list.total = val.length;
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    format,
    hasRouteAuth,
    signStatusFilter,
    getSignUpColor,
    selectAccount(data) {
      this.list.items = data;
      this.list.total = data.length;
      this.showAccountSelection = false;
      const ids = data.map(item => item.mediumId).join(',');
      this.resourceAssociation(ids);
    },
    getColor(status) {
      status = this.signStatusFilter(status);
      return this.getSignUpColor(status);
    },
    resourceAssociation(ids) {
      resourceAssociation(this.supplierId, { ids }).then(res => {
        if (res.code === 200) {
          this.$emit('updateData');
        }
      }).catch(err => console.error(err));
    },
    openLink(val) {
      if (/^(www)/i.test(val)) {
        val = `https://${val}`;
        window.open(val);
        return;
      } else if (val && this.testUrl(val)) {
        window.open(val);
        return;
      }
      this.$message.warning('无效的链接');
    },
    // 跳转详情
    toContractDetail(data) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(data.businessId) },
        query: { processId: encryption(data.processId) }
      });
      window.open(routeUrl.href, '_blank');
    },
    // 跳转账号详情
    toAccountDetail(id) {
      if (!this.hasRouteAuth('medium:resource:admin')) {
        this.$message.warning('暂无资源可读权限，请联系管理员开通');
        return;
      }
      const url = this.$router.resolve({
        name: 'detailResource',
        params: { resourceId: id }
      });
      window.open(url.href, '_blank');
    },
    addAccount() {
      this.$refs['accountSelection'].init(this.list.items);
      this.showAccountSelection = true;
    },
    toCreate() {
      const { supplier, supplierType } = this.supplierDetailInfo;
      const routeUrl = this.$router.resolve({
        name: 'resource',
        query: {
          toCreate: 1,
          supplier,
          supplierId: this.supplierId,
          supplierType
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    handleBatchDelete() {
      const ids = this.multipleSelectionAll.map(item => item.mediumId).join(',');
      if (!ids) {
        this.$message.warning('请选择要取消关联的账号');
        return;
      }
      this.handleDelete(ids);
    },
    handleDelete(ids) {
      this.$confirm('是否确定取消关联', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        delResource(this.supplierId, { ids }).then(res => {
          if (res.code === 200) {
            this.$emit('updateData');
            if (this.clearMixinSelection) this.clearMixinSelection();
            this.$message.success('操作成功');
          }
        }).catch(err => {
          console.error(err);
        });
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
    }
  }
};
</script>

<style scoped lang="scss">
.el-col {
  .el-form-item {
    border-right: 1px solid #eee;
  }
}
.el-col:nth-child(odd) {
  .el-form-item {
    border-right: none;
  }
}
.account-info-container {
  background-color: #fff;
  padding: 16px 24px 32px 24px;
  .title-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    .title-head {
      flex: unset;
    }
  }
  ::v-deep .empty-class {
    padding: 0;
  }
  .select-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .list-tab{
    padding: 0 0 0 8px !important;
    ::v-deep .item-content {
      padding: 16px 0 8px !important;
    }
  }
  &::v-deep {
    .el-form-item {
      margin-bottom: 0;
    }
    .el-form-item__label {
      line-height: 30px;
      color: #999;
    }
    .el-form-item__content {
      line-height: 30px;
    }
  }
  .tip-content {
    font-size: 12px;
    //color: #141C3D;
    color: #FF4E5F;
    background-color: #f9f9f9;
    padding: 8px;
    margin-bottom: 12px;
    line-height: 1.5em;
    text-align: justify;
  }
  .form-content {
    flex-wrap: wrap;
    margin-bottom: 20px;
    .section-title {
      font-size: 16px;
      color: #333;
      font-weight: bold;
      padding-left: 8px;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      .dot {
        width: 4px;
        height: 4px;
        background-color: #406EFF;
        margin-right: 6px;
      }
    }
    .info-col-item {
      //border-right: 1px solid #EBEEFD;
      // ::v-deep img {
      //   margin-top: 8px;
      // }
      &::v-deep {
        .info-icon-img {
          img {
            margin-top: 0;
          }
        }
      }
      .account-tags {
        display: flex;
        flex-wrap: wrap;
        .tag {
          cursor: pointer;
          white-space: nowrap;
          color: #406eff;
          background-color: #eff3fb;
          padding: 2px 8px;
          font-size: 12px;
          border-radius: 2px;
          margin-right: 8px;
        }
        .tag:hover {
          opacity: .7;
        }
      }
      .account-info-link {
        display: flex;
        align-items:center;
        color: #406eff;
        img {
          margin-top: 1px;
          width: 11px;
          margin-left: 3px;
        }
      }
      .form-item-block {
        display: inline-block;
        max-width: calc(100% - 25px);
        vertical-align: top;
      }
    }
    ::v-deep .ellipsisOne {
      width: 100%;
    }
    //.info-col-item:nth-child(2n + 1) {
    //  border-right: none;
    //}
  }
  .form-content:nth-child(n+1) {
    margin-top: 6px;
  }
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
    .empty-text {
      font-size: 14px;
      font-weight: 400;
      text-align: left;
      color: #999999;
      line-height: 20px;
      margin-top: 10px;
    }
    img {
      width: 120px;
    }
  }
  .operate-delete {
    cursor: pointer;
    color: #406eff;
  }
}
</style>
